// 统一消息处理器 unifiedHandler.js
const roomService = require('../services/roomService');
const gameService = require('../services/gameService');

class UnifiedHandler {
  constructor() {
    this.connections = new Map(); // 存储用户ID和WebSocket连接的映射
    this.errorCodes = {
      ROOM_NOT_FOUND: 1001,
      PLAYER_NOT_READY: 1002,
      PLAYER_OFFLINE: 1003,
      // ... 更多错误码
    };
  }

  handleConnection(ws) {
    ws.on('message', (message) => {
      try {
        const data = JSON.parse(message);
        this.handleMessage(ws, data);
      } catch (error) {
        console.error('处理WebSocket消息错误:', error);
      }
    });

    ws.on('close', () => {
      // 找到并移除断开连接的用户
      for (const [userId, socket] of this.connections.entries()) {
        if (socket === ws) {
          this.connections.delete(userId);
          this.handleUserOffline(userId);
          break;
        }
      }
    });
  }

  handleMessage(ws, data) {
    const { phase, type, payload } = data;
    
    if (phase === 'ROOM_PHASE') {
      this.handleRoomPhase(ws, type, payload);
    } else if (phase === 'GAME_PHASE') {
      this.handleGamePhase(ws, type, payload);
    }
  }

  // 房间阶段处理器
  handleRoomPhase(ws, type, payload) {
    switch (type) {
      case 'JOIN_ROOM':
        this.handleJoinRoom(ws, payload);
        break;
      case 'UPDATE_ONLINE_STATUS':
        this.handleOnlineStatus(payload);
        break;
      case 'PLAYER_READY':
        this.handlePlayerReady(ws, payload);
        break;
      case 'START_GAME':
        this.handleStartGame(ws, payload);
        break;
    }
  }

  // 游戏阶段处理器
  handleGamePhase(ws, type, payload) {
    switch (type) {
      case 'JOIN_GAME':
        this.handleJoinGame(ws, payload);
        break;
      case 'PLAY_CARD':
        this.handlePlayCard(ws, payload);
        break;
      case 'MAKE_PREDICTION':
        this.handlePrediction(ws, payload);
        break;
      //  等等其他阶段
    }
  }

  async handleStartGame(ws, payload) {
    try {
      const { roomNumber } = payload;
      
      // 1. 获取房间信息
      const room = await roomService.getRoom(roomNumber);
      if (!room) {
        throw new Error('房间不存在');
      }
  
      // 2. 验证开始游戏条件
      if (room.players.length !== 3) {
        throw new Error('玩家人数不足');
      }
  
      const owner = room.owner;
      const allPlayersReady = room.players.every(p => 
        p.id === owner || p.isReady
      );
      
      if (!allPlayersReady) {
        throw new Error('有玩家未准备');
      }
  
      // 3. 检查所有玩家是否在线
      const allPlayersOnline = room.players.every(p => p.isOnline);
      if (!allPlayersOnline) {
        throw new Error('有玩家未在线');
      }
  
      // 4. 创建游戏实例
      const game = gameService.createGame(roomNumber, room.players.map(p => p.id));
      
      // 5. 更新房间状态
      room.status = 'IN_GAME';
      
      // 6. 广播游戏开始消息，根据实际的game结构修改
      this.broadcastToRoom(roomNumber, {
        type: 'PHASE_CHANGE',
        payload: {
          newPhase: 'GAME_PHASE',
          roomNumber: roomNumber,  // 使用房间号代替gameId
          gameInfo: {
            roomNumber: game.roomNumber,
            players: game.players,
            deck: game.deck,
            currentPlayerIndex: game.currentPlayerIndex,
            roundNumber: game.roundNumber,
            gameState: game.gameState,
            scores: game.scores
          }
        }
      });
  
    } catch (error) {
      console.error('开始游戏错误:', error);
      ws.send(JSON.stringify({
        type: 'ERROR',
        payload: error.message
      }));
    }
  }

  // 广播消息到房间
  broadcastToRoom(roomNumber, message) {
    const room = roomService.rooms.get(roomNumber);
    if (!room) return;

    room.players.forEach(player => {
      const ws = this.connections.get(player.id);
      if (ws && ws.readyState === 1) {
        ws.send(JSON.stringify(message));
      }
    });
  }

  async handleJoinRoom(ws, payload) {
    try {
      const { roomNumber, userId } = payload;
      
      // 1. 存储WebSocket连接
      this.connections.set(userId, ws);
      
      // 2. 获取房间信息
      const room = await roomService.getRoom(roomNumber);
      if (!room) {
        throw new Error('房间不存在');
      }
      
      // 3. 验证玩家是否已在房间中
      const existingPlayer = room.players.find(p => p.id === userId);
      if (!existingPlayer) {
        throw new Error('玩家不在房间中');
      }
      
      // 4. 广播房间更新消息给所有玩家
      this.broadcastToRoom(roomNumber, {
        type: 'ROOM_UPDATE',
        payload: room
      });
      
      // 5. 单独发送确认消息给加入的玩家
      // ws.send(JSON.stringify({
      //   type: 'JOIN_ROOM_SUCCESS',
      //   payload: {
      //     room,
      //     userId
      //   }
      // }));

    } catch (error) {
      console.error('处理加入房间错误:', error);
      ws.send(JSON.stringify({
        type: 'ERROR',
        payload: error.message
      }));
    }
  }

  handleOnlineStatus(payload) {
    const { roomNumber, userId, isOnline } = payload;
    const room = roomService.getRoom(roomNumber);
    if (!room) return;
  
    const player = room.players.find(p => p.id === userId);
    if (player) {
      player.isOnline = isOnline;
      
      // 广播在线状态更新
      this.broadcastToRoom(roomNumber, {
        type: 'ONLINE_STATUS_UPDATE',
        payload: {
          userId,
          isOnline
        }
      });
    }
  }

  async handlePlayerReady(ws, payload) {
    try {
      const { roomNumber, userId, isReady } = payload;
      
      // 1. 更新玩家准备状态
      const room = await roomService.updatePlayerReady(roomNumber, userId, isReady);
      if (!room) {
        throw new Error('房间不存在');
      }
  
      // 2. 检查是否所有非房主玩家都已准备
      // const owner = room.owner;
      // const allPlayersReady = room.players.every(p => 
      //   p.id === owner || p.isReady
      // );
      
      // 计算未准备的玩家数量（不包括房主）
      const unreadyCount = room.players.filter(p => p.id !== owner && !p.isReady).length;

      // 如果没有未准备的玩家，并且房间内玩家数量大于1（至少有房主和其他玩家），则可以开始
      const canStart = unreadyCount === 0 && room.players.length > 1;

      // 3. 广播房间状态更新
      this.broadcastToRoom(roomNumber, {
        type: 'ROOM_UPDATE',
        payload: {
          ...room,
          canStart: canStart
        }
      });
  
    } catch (error) {
      console.error('处理玩家准备状态错误:', error);
      ws.send(JSON.stringify({
        type: 'ERROR',
        payload: error.message
      }));
    }
  }

  sendError(ws, code, message) {
    ws.send(JSON.stringify({
      type: 'ERROR',
      payload: {
        code,
        message
      }
    }));
  }
}

// 新增处理在线状态更新的方法


module.exports = UnifiedHandler;